/**
  ******************************************************************************
  * @file    main.c
	* @author  MCU SYSTEM Team
	* @Version V1.0.0
  * @Date    2020-10-19
  * @brief   main function
  ******************************************************************************
  */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

#include "flash_drv.h"
#include "sys_clk_drv.h"
#include "rtc_drv.h"
#include "pwr_drv.h"
#include "TM1616_drv.h"
#include "bat_drv.h"
#include "motor_drv.h"
#include "coder_drv.h"
#include "timer_drv.h"
#include "uart_drv.h"
//
//



#define DEBUG_MODE		false
#define My_Test         1



const char APP_VER[]="SAS936ZHB_7_Z03 V1.0.0-20240809";
extern volatile  uint32_t DebugCount;

//ssssssssssssssssssssssssssssssssssssssssssss
//ssssssssssssssssssssssssssssssssssssssssssss
//ssssssssssssssssssssssssssssssssssssssssssss
//ssssssssssssssssssssssssssssssssssssssssssss
//ssssssssssssssssssssssssssssssssssssssssssss
//ssssssssssssssssssssssssssssssssssssssssssss
//ssssssssssssssssssssssssssssssssssssssssssss
//ssssssssssssssssssssssssssssssssssssssssssss//ssssssssssssssssssssssssssssssssssssssssssss
//ssssssssssssssssssssssssssssssssssssssssssss
/*

bool MCUStatus = 1;			//1����״̬������״̬

bool MCUStatus1 = 0;			//1����״̬������״̬
extern volatile bool EncoderChangeFlag;
volatile uint32_t zigbeeTimeout = 0;

*/

bool MCUStatus = 1;			//1����״̬������״̬

bool MCUStatus1 = 0;			//1����״̬������״̬
extern volatile bool EncoderChangeFlag;
volatile uint32_t zigbeeTimeout = 0;


*/

bool MCUStatus = 1;			//1����״̬������״̬

bool MCUStatus1 = 0;			//1����״̬������״̬
>>>>>>> refs/remotes/origin/master
extern volatile bool EncoderChangeFlag;
volatile uint32_t zigbeeTimeout = 0;


static void MCU_DeepSleep(void);
static void Display_Version(uint8_t num1,int8_t num2);
static void MUC_Config_init(void);
static void System_parameter_Init(void);


/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void Error_Handler(void);

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{   
	static volatile uint8_t firsttime = 1;
    // ��λ�������裬��ʼ��flash�ӿں�systick.
    HAL_Init();

    MUC_Config_init();            //


    System_parameter_Init();
    //ZIGBEE_REST_H;				//zigbeeģ�鿪ʼ�˳���λģʽ
    //����PA08����ΪMCO���ܣ����ϵͳʱ��
    // HAL_RCC_MCOConfig(0,RCC_MCO1SOURCE_SYSCLK,RCC_MCODIV_1);
    //����ϵͳʱ��ΪHSE��HCLK�ķ�Ƶ��PCLK����Ƶ
    //SystemClock_Config();
    ZIGBEE_REST_H;				//zigbeeģ�鿪ʼ�˳���λģʽ
    HAL_DBGMCU_EnableDBGMCUStopMode();

    NextProgramSeg = Start_ProgramFCT();


    zigbeeTimeout  = 30;//��λ��ʼ��ʱ�䣬30��
    while (1)
    {
#if (DEBUG_MODE != true)
#if (My_Test == 1)
        fwdt_drv_feed_wdt();	         //��������ʱ��ת��������40�뵼�¿��Ź���λ
#endif
#endif
        Key_Value_Process();	         //������ȡ
        FLAG_MOTOR_STALL_CHECK  = TRUE;  //����ת
        Motor_Sample_Handle();           //�����ת���
        fptKeyProcessFCT();              //ҳ�水����������ָ�룬��������
        MainPageEncoderProcessFCT();     //����������

        /////zigbee���뿪ʼ///

        time_management();               //ʱ��������������RTC���Ѵ�������
        Rf_int_Data();                   //�������ݳ�ʼ�ϱ�
        RF_Receive_Data();               //���ݽ��մ���
		RF_SendData_Processing();        //�����ط����ƴ���

        //Zigbee_Return_status();

        History_Data_set();//�µ��ϱ���ʷ��¼
        RF_Report();//���ݱ�ԭ��������

        //zigbee�������///

        //20�����ڿ���
        if (RTC_60sIrqflg == true)			//RTC20s�����жϲɼ��¶Ⱥ͵�ص�ѹ
        {
            rtc_drv_get_rtc_time();
            if (Motortype == Type_Stop && Flag_LEDDisplayON == FALSE )//&& RF_Sleep_Flag == TRUE)//���������RF�����ڼ䲻��ADC�ɼ�����
            {
                RTC_cyccnt = 0;//Ϊ������RF T2����ͬ��������MCU�Ļ��Ѵ���
                Battery_Check();//��ص�ѹ�ɼ�
                Get_RoomTemperature();//�¶Ȳɼ�

                if(firsttime ==1)//��һ�βɼ��¶ȣ�ѧϰ���жϱ�׼
                {
                    firsttime =0;
                    SystemTemp.WdCmpTemp = SystemTemp.RoomTemp;
                }
#if Not_888
                if(SystemWorkStatus ==TRUE)//����������⣬�ػ�״̬�����
                {
                    Windows_Check();//�������
                }
                if(Motor_Learned_Flag == TRUE)//���ѧϰ��ɲ��ܶ����
                {
                    control_output();//
                }
                if(Motor_Learned_Flag == TRUE)//���ѧϰ��ɲ��ܶ����
                {
#if(My_Test == 1)
                    set_motor_output();//
#endif
                }

                WindowsOpenTimerBreak(SystemClock.u8Minute);
#endif
                RTC_60sIrqflg = false;
            }
        }

        rtc_drv_one_second_handler();

        prog_programme_run();

        if(AlarmFlag == true)//������Ӵ���
        {
            AlarmFlag = false;
            NextProgramSeg = Start_ProgramFCT();//��ȡ��̵�ǰ���жε�����,����������һ�β�������
            RF_Prog_Up();
            if(SetSystempMode != Manual_Mode)//����������ֻ�з��ֶ�ģʽ�Ż��������ӹ���
            {
#if Not_888
                OutputMode = OUTPUT_MODE_CHANGE_SET_TEMP; //���ģʽ���п��ܸı��¶ȣ��޸�Ϊ�޸����¶�ģʽ
#endif
            }
        }

        //LED��ʾ����
        if(DeepSleep_OutCNT>0)// && Battery_Status == Bat_Vol_normal)//���ӵ�ص�ѹ��������ʾ //@20200107
        {
            LEDPW_Enable(TRUE);//�򿪵�Դ
            LED_Work = TRUE;

            //��ʾˢ��
            if(LED_ReFresh == TRUE)//LEDs��ʾˢ�±�־
            {
                LED_ReFresh = FALSE;//LEDs��ʾˢ�±�־���
                fptDiplayFCT();//��ʾ��������ָ��
            }
        }
        else//LED��ʾʱ�����
        {
            if(LED_Work == TRUE)//if(Debug != Debug2 || TestFCT == Test_Stop)
            {
                TM1616send_command(0x80);//������ʾ�أ�ռ�ձ�1/16.
                //�ر�LED
                LEDPW_Enable(FALSE);//�ر�LED��Դ
                TM1616_CLK_L;
                TM1616_STB_L;
                TM1616_DIO_L;
                LED_Work = FALSE;
            }
        }
#if Not_888
        //û��ʱ��������¹�ͣ���/////
        if (Motortype == Type_Stop)//���ֹͣ״̬
        {
            if (HAL_GPIO_ReadPin(MOTOR_ADD_PORT, MOTOR_ADD_PIN) != 0  ||
                    HAL_GPIO_ReadPin(MOTOR_REDUCE_PORT, MOTOR_REDUCE_PIN) != 0)		//����io���ǵ͵�ƽ
            {
                motor_Stop();				//�رյ��
                systick_delay_us(1);		//�رյ������ʱ10us����Ҫ��io��Ӧʱ��
            }
        }
#endif
        MCU_DeepSleep();					//���߿���
    }
}



//MUC ���ó�ʼ��
static void MUC_Config_init(void)
{
    static uint32_t debug_count = 0;
    uint16_t i;
    uint8_t battery_count = 0;

    system_clock_config();              //�ڲ�����

    HAL_FLASH_Init(FLASH_PROGRAM_ERASE_CLOCK_24MHZ);                                 //��ʼ��Flashʱ��,��Ҫ��HSIʱ�ӱ���һ��,���߿��ܲ�дʧ��
    systick_delay_ms(1000);


    boost_power_init();             //��ѹ�˿ڳ�ʼ��

    Init_RoomTempADCIO();			//�����¶Ȳɼ����IO��ʼ��

    /***************��ز���io���ü�����������ʼ��********/
    // bat_drv_bat_gpio_init();		//��ص�ѹ���IO
    Battery_Status = Bat_Vol_normal;//�����︳ֵλ�����ģ������ʼ��ADC�ڣ���Ҫ�ٴε���
    /*****************************************************/
#if Not_888
    motor_current_gpio_init();      //�����ת������ʼ��
#endif
    My_Key_Gpio_init();  			//����IO��ʼ�����������ⲿ�ж�
#if Not_888
    coder_drv_coder_init();			//���̱�����io��ʼ��
	
    motor_drv_motor_gpio_init();	//������IO��ʼ��
#endif
    TM1616_gpio_init();				//��ʼ��TM1616���gpio
	
    timer16_init();					//zigbee �����ж��Ƿ���Ҫ�ط�
	
    uart_drv_zigbee_uart_init();    //���ڳ�ʼ��

    zigbee_gpio_init();             //zigbee ���ѽų�ʼ��

    STOP_gpio_DELLWITH();           //����û���õĶ˿�

    rtc_drv_rtc_init();				//RTCʱ�ӳ�ʼ��
	
    rtc_drv_rtc_init1();			//RTCʱ�ӳ�ʼ��1

    while (1)						//��ص���2.2V������
    {
        //����ص�ѹ
        if(Battery_Check_Pwrup()>=2000) //С��2.2V������
        {
            battery_count++;
        }
        else
        {
            battery_count =0;
        }
        if(battery_count>=10)
        {
            break;
        }
        systick_delay_ms(10);
    }

    for (i = 0; i < 20; i++)				//�жϰ�������  �ϵ�ɼ�1��
    {
        if (Key_Up == FALSE)
        {
            debug_count++;
        }
        systick_delay_ms(50);
    }
    if (debug_count>=10)                    //�а�������
    {
        Debug = Debug2;                     //����ģʽ
    }
    else
    {
        Debug = Debug1;
    }

    if(Debug == Debug2)
    {
        DebugCount =0;
        timer3_init();                       //�������ṩ��ʱ
        Init_EnterTestFCT();                 //���Խ���
        LED_ReFresh = TRUE;
    }
    Debug = Debug1;

    if (Debug == Debug1)
    {
        exti_interrupt_enable_ctrl(KEY_EXTI_LINE, SEL_EN);  //�����ж�

        Init_EnterMainWorkPage();
    }
	/*
		�ڴ�֮ǰ������û�п����жϵ�
	*/
}



//ϵͳ������ʼ��
static void System_parameter_Init(void)
{
    //uint8_t i;
    systick_delay_ms(100);
    Init_NTC_ADCValues();				            //��ʼ���¶ȴ�����
    memset(&SystemErrFlag, 0, sizeof(Typedefu8Bit));//ϵͳ����״̬����
    memset(&SystemFlag, 0, sizeof(Typedefu8Bit));   //ϵͳ״̬����

    RF_Parameter_init();			                // zigbee��־��������ʼ��
    MCUStatus = 1;					                //MCU���ڻ���״̬
    RTC_60sIrqflg = true; 			                //�ϵ���Ҫȥ��ʱ����¶� һ�����жϱ�ʶ
    LED_ReFresh = TRUE; 			                //LED��ʾˢ��ʹ��
    Flag_LEDDisplayON = FALSE;		                //@20200109 LED������ʶ
#if Not_888
    output_set.windows_flag=FALSE;	                //@debug_window ����
#endif
    rtc_drv_get_rtc_time();			                //��ֵRTC
    Flash_SystemStart();			                //��Flash��ȡ��ǰ��״̬
    /*************�ϵ�������ֶ�ģʽ**********************************/
    if(SetSystempMode != Manual_Mode)               //����Ƿ��ֶ�ģʽ
    {
        ProgramAutoModeFlag = TRUE;                 //��������Ҫ�л����Զ�ģʽ
        SetSystempMode = Manual_Mode;               //�����ֶ�ģʽ
    }

    Get_RoomTemperature();                          //�ϵ��ȡ�¶�
    if (Battery_Check_Pwrup()<= BATT_CHECK_PWR)     //��ص�ѹ ѧϰǰ��һ��ͳһ��� 
    {
        BattStartLowFlag = TRUE;                    //���������ѹ����
    }
    else
    {
        BattStartLowFlag = FALSE;                   //���������ѹ��
    }

    Display_Version(DISPLAY_U, DISPLAY_1);          //��ʾ�汾�� ��Ҫ�޸�

    if(Debug != Debug2)                             //û�������������Գ���
    {
#if (DEBUG_MODE != true)
#if (My_Test == 1)
#if Not_888
        motor_install();                            //�����λ����ѧϰ�г�
#endif
#endif
#endif
    }

    if(Debug == Debug1)
    {
        output_set.scale_hour = 366;                //����ģʽ�£���ˮ������ʱ��ʼֵΪ365Сʱ
    }
    else
    {
        output_set.scale_hour = 365;                //����ģʽ�£���ˮ������ʱ��ʼֵΪ366Сʱ
    }
    Init_KeyParameter();
    DeepSleep_OutCNT = Wake_Up_5Senconds;
    LED_ReFresh = TRUE;
    Start_Timer1();                                 //������ʱ�������ڵ��ð���������
    timer3_init();                                  //�������ṩ��ʱ


#if (DEBUG_MODE != true)
#if (My_Test==1)
    fwdt_drv_wdt_init();		                    //ע�ⲻҪ��ѧϰ����г�֮ǰ����   ���Ź�
#endif
#endif
}
//������߿���
static void MCU_DeepSleep(void)
{
    Judging_Data();  //�ж����ݷ������
#if (My_Test!=1)
	return;
#endif
    if (LED_Work != FALSE || RTC_60sIrqflg != FALSE || (Rf_Sleep_Time > 0) || (DataIsSentFlag == 1) || zigbeeTimeout > 0||RF_Report_Flag) 
	{
        return;
    }
	//����͹��Ĵ���
    if (Flag_SystemStatusChange == TRUE)			//ϵͳ�������޸�
    {
        Flag_SystemStatusChange = FALSE;
        My_FlashSystemData_Write();					//���µ�ϵͳ����д��Flash
    }
    /*****************��������¹�ͣ���***************************************/
#if Not_888
    motor_Stop();				                    // �رյ��
#endif
    systick_delay_us(10);		                    //�رյ������ʱ10us����Ҫ��io��Ӧʱ��

    MCUStatus = 0;				                    //MCU��������״̬

    while(DeepSleep_OutCNT == 0 && RTC_60sIrqflg == FALSE \
            && Rf_Sleep_Time==0 )                   //&& RF_PIN_WAKE==TRUE)
    {

        time_management();                          //ʱ��������������޴ε���
        fwdt_drv_feed_wdt();	//
        //PWR
        //   __HAL_RCC_USART1_CLK_DISABLE();

        __HAL_RCC_PWR_CLK_ENABLE();

        SET_BIT(PWR->CR1,PWR_CR1_VOS);

        HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI); //stop mode ����͹���
        MCUStatus1=1;
    }

    systick_delay_ms(3);
    uart_drv_zigbee_uart_init();
	//���ñ���
    if(MCUStatus1)
    {
        //�л�ϵͳʱ��ΪHSE�ⲿ����ʱ��
        MCUStatus1=0;
    }
    if(MCUStatus == 0)
    {
        MCUStatus = 1;//MCU���ڻ���״̬
    }

}



//��ʾ�汾��
static void Display_Version(uint8_t num1,int8_t num2)
{
    uint8_t Dp_Num[4] = {0x7F,0x7F,0x7f,0x00};

    LEDPW_Enable(true);				//�򿪹��翪��

    //ȫ��
    TM1616_Display(Dp_Num);
    systick_delay_ms(2000);

    //ȫ��
    Dp_Num[0] = 0x00;
    Dp_Num[1] = 0x00;
    Dp_Num[2] = 0x00;
    Dp_Num[3] = 0x00;
    TM1616_Display(Dp_Num);
    systick_delay_ms(500);
    //��ʾ�汾��
    if (SetLedMode == TRUE) {
        Dp_Num[0] = Seg_Table[num1];
        Dp_Num[1] = Seg_Table[num2];
        Dp_Num[2] = 0<< 5;//�ַ�5��ʾ
        Dp_Num[3] = 0x00;
        TM1616_Display(Dp_Num);
        systick_delay_ms(2000);

    } else {
        Dp_Num[0] = Seg_Table1[num2];
        Dp_Num[1] = Seg_Table1[num1];
        Dp_Num[2] = 0;//�ַ�5��ʾ����ʾ
        Dp_Num[3] = 0x00;
        TM1616_Display(Dp_Num);
        systick_delay_ms(2000);
    }

    LED_ReFresh = TRUE;
}






/* Private function -------------------------------------------------------*/

uint16_t NTCResistorValue(uint16_t ADCBuff, uint16_t PullUpResistor)
{
    double Rntc_result;
    uint16_t ADC_DIF_Values = 0;//
    Rntc_result = 0x0fff-ADC_DIF_Values-ADCBuff;//�������������ADCֵ
    Rntc_result = ADCBuff/Rntc_result;//����NTC����ֵ����������ı�ֵ
    Rntc_result *= PullUpResistor;//NTC����ֵ���������������ֵ * ��ֵ
    return (uint16_t)Rntc_result;
}


uint16_t ResistorValue(uint16_t ADCBuff, uint16_t PullUpResistor)
{
    double Rntc_result;
    uint16_t ADC_DIF_Values = 0;//
    Rntc_result = 0x0fff-ADC_DIF_Values-ADCBuff;//�������������ADCֵ
    Rntc_result = ADCBuff/Rntc_result;//����NTC����ֵ����������ı�ֵ
    Rntc_result *= PullUpResistor;//NTC����ֵ���������������ֵ * ��ֵ
    return (uint16_t)Rntc_result;
}

